<template>
  <div class="app-container">
    <!-- <el-avatar :src = "fileContent"></el-avatar> -->
    <div class="filterContainer">
      <el-input v-model="listQuery.title" placeholder="姓名" style="width: 200px; margin-right: 10px" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>
    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label="头像" width="120">
        <template slot-scope="scope">
          <el-avatar :size="40" shape="square"
            :src="scope.row.avatar ? 'http://localhost:3001/image/avatars/' + scope.row.avatar : circleUrl"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column align="center" label="姓名" width="120">
        <template slot-scope="scope">
          {{ scope.row.teacher_name }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="工号" width="120">
        <template slot-scope="scope">
          {{ scope.row.teacher_id }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户名" width="120">
        <template slot-scope="scope">
          {{ scope.row.user_name }}
        </template>
      </el-table-column>
      <el-table-column label="学院" width="120">
        <template slot-scope="scope">
          {{ scope.row.institute_name }}
        </template>
      </el-table-column>
      <el-table-column label="教师经历" align="center">
        <template slot-scope="scope">
          <el-popover placement="top-start" width="250" trigger="hover" :content="scope.row.teacher_experience">
            <span slot="reference"
              style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;width: 100px;display: inline-block;">
              {{ scope.row.teacher_experience }}
            </span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="个性签名" align="center">
        <template slot-scope="scope">
          {{ scope.row.signature }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status != 'deleted'" size="mini" type="danger" @click="handleDelete(row, $index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
      @pagination="fetchData" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" class="dialog">
      <div class="dialog">
        <el-form ref="dataForm" :model="teacherInfo" label-position="left" label-width="90px" style="width: 80%">
          <el-form-item class="upload" label="头像：">
            <div style="
                display: flex;
                justify-content: center;
                align-items: center;
              ">
              <el-avatar :size="50" v-show="dialogStatus == 'update' && !fileContent"
                :src="teacherInfo.avatar ? 'http://localhost:3001/image/avatars/' + teacherInfo.avatar : squareUrl"
                shape="square" :img="teacherInfo.avatar" style="margin-right: 40px"></el-avatar>
              <el-avatar :size="50" v-show="dialogStatus == 'update' && fileContent" :src="fileContent" shape="square"
                :img="fileContent" style="margin-right: 40px"></el-avatar>
              <el-avatar :size="50" v-if="dialogStatus == 'create'" :src="fileContent ? fileContent : squareUrl"
                shape="square" style="margin-right: 40px"></el-avatar>
              <!-- <input type="file" id="image" @change="selectImg" style="display: none" /> -->
              <el-button @click="show" id="btn" style="display: none;"></el-button>
              <!-- <label for="image"> -->
              <label for="btn">
                <div style="
                    width: 100px;
                    height: 35px;
                    backgroundColor: #409eff;
                    cursor: pointer;
                    color: #fff;
                    border-radius: 5px;
                    text-align: center;
                    line-height: 35px;
                    font-weight: 500
                  ">
                  点击上传
                </div>
              </label>
            </div>
          </el-form-item>
          <el-form-item prop="teacherInfo" label="院校信息:">
            <el-select v-model="teacherValue" placeholder="请选择">
              <el-option v-for="item in teacherInfoData" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="dialogStatus == 'create'" label="姓名:">
            <el-input v-model="teacherInfo.teacher_name" placeholder="姓名" />
          </el-form-item>
          <el-form-item v-if="dialogStatus == 'update'" label="用户名:">
            <el-input v-model="teacherInfo.user_name" placeholder="用户名" />
          </el-form-item>
          <el-form-item v-if="dialogStatus == 'create'" label="工号:">
            <el-input v-model="teacherInfo.teacher_id" placeholder="工号" />
          </el-form-item>
          <el-form-item label="个人经历:">
            <el-input v-model="teacherInfo.teacher_experience" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
              placeholder="请输入您的个人经历" />
          </el-form-item>
          <el-form-item label="个性签名:">
            <el-input v-model="teacherInfo.signature" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
              placeholder="请输入您的个性签名" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false"> Cancel </el-button>
          <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
            Confirm
          </el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 图片裁剪弹框 -->
    <Cropper :dialogCropper="dialogCropper" :imgUrl="nowAvatar" :fixedNumber="[1, 1]" :loading="loading"
      @closeDialog="dialogCropper = false" @blobData="handleBlobData" v-if="nowAvatar">
    </Cropper>
  </div>
</template>

<script>
import {
  getTeacher,
  getTeacherOptions,
  addTeacher,
  editTeacher,
  deleteTeacher
} from "@/api/userTable";
import Pagination from "@/components/Pagination";
import { mapGetters } from "vuex";
// import * as imageConversion from 'image-conversion';
import Cropper from "@/components/Cropper/Cropper";

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger",
      };
      return statusMap[status];
    },
  },
  components: {
    Pagination,
    Cropper
  },
  data() {
    return {
      list: null,
      listLoading: true,
      circleUrl:
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      squareUrl:
        "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
      total: 0,
      // 传递的页号
      listQuery: {
        pageNum: 1,
        pageSize: 20,
      },
      nowAvatar: "",
      downloadLoading: false,
      dialogStatus: "",
      dialogFormVisible: false,
      rules: [],
      teacherInfo: {
        signature: "",
        teacher_name: "",
        teacher_id: "",
        user_name: "",
        teacher_experience: ""
      },
      textMap: {
        update: "编辑老师",
        create: "添加老师",
      },
      teacherValue: "",
      teacherInfoData: [],
      fileList: [],
      user_id: '',
      fileContent: '',
      // 裁剪组件的基础配置option
      dialogCropper: false,
      loading: false,
    };
  },
  created() {
    this.fetchData();
    this.getOptions();
  },
  computed: {
    ...mapGetters(["sidebar", "avatar"]),
  },
  methods: {
    // 获取数组信息(已修改)
    fetchData() {
      this.listLoading = true;
      getTeacher(this.listQuery).then((response) => {
        this.list = response.data.items;
        this.total = response.data.total;
        console.log(response.data.items);
        this.listLoading = false;
      });
    },
    // 获取学院（已修改）
    getOptions() {
      getTeacherOptions().then((response) => {
        console.log(response);
        this.teacherInfoData = response.infoData;
      });
    },
    // 将内容进行重置(已修改)
    reset() {
      this.fileData = {};
      this.teacherValue = '';
      this.teacherInfo.signature = '';
      this.teacherInfo.teacher_name = '';
      this.teacherInfo.teacher_id = '';
      this.teacherInfo.user_name = '';
      this.fileContent = '';
    },
    // 点击添加按钮触发
    handleCreate() {
      this.reset()
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 搜索按钮
    handleFilter() { },
    // 导出下载
    handleDownload() { },
    // 选择学生信息的时候调用
    handleChange() { },
    // 点击编辑按钮调用
    handleUpdate(row) {
      this.reset();
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
      console.log(row)
      this.teacherInfo = { ...row }
      this.teacherValue = row.institute_id
      this.user_id = row.user_id;
    },
    // 添加学生点击提交(前端已修改)
    createData() {

      let obj = { ...this.teacherInfo };
      obj.institute_id = this.teacherValue;

      addTeacher(obj, this.fileData).then(response => {
        if (response.code == 200) {
          this.dialogFormVisible = false;
          this.fetchData();
        }
      })
    },
    // 编辑学生点击提交
    updateData() {
      let obj = {};
      obj.institute_id = this.teacherValue;
      obj.user_id = this.user_id;
      obj.signature = this.teacherInfo.signature
      obj.user_name = this.teacherInfo.user_name;
      obj.teacher_experience = this.teacherInfo.teacher_experience;
      console.log(obj, "发送的对象");
      editTeacher(obj, this.fileData).then((response) => {
        console.log(response)
        if (response.code == 200) {
          this.dialogFormVisible = false;
          console.log("此时重新进行查询");
          this.fetchData();
          this.loading = false
        }
      });
    },
    show() {
      console.log(this.teacherInfo.avatar);
      if (this.teacherInfo.avatar) {
        this.nowAvatar = 'http://localhost:3001/image/avatars/' + this.teacherInfo.avatar
      } else {
        this.nowAvatar = this.squareUrl
      }
      // this.nowAvatar = this.teacherInfo.avatar ? 'http://localhost:3001/image/avatars/' + this.teacherInfo.avatar : this.squareUrl
      console.log(this.nowAvatar);
      this.dialogCropper = true
    },
    // 裁剪图片后返回的blob
    async handleBlobData(blob) {
      // 处理 Blob 对象
      console.log(blob);
      const reader = new FileReader();
      reader.onload = () => {
        this.fileContent = reader.result;
      };
      reader.readAsDataURL(blob);
      let fd = new FormData()
      fd.append('avatar', blob)
      this.fileData = fd;
      console.log(this.fileData);
    },
    // 选择图片
    // async selectImg(e) {
    //   const file = e.target.files[0];
    //   const reader = new FileReader();
    //   reader.onload = () => {
    //     this.fileContent = reader.result;
    //   };
    //   reader.readAsDataURL(file);
    //   let fd = new FormData();
    //   let fileList = e.target.files;
    //   let obj = await this.ReadData(fileList[0]);
    //   console.log(obj)
    //   fd.append("avatar", obj);
    //   this.fileData = fd;
    //   console.log(fd.get("avatar"))
    // },
    // 图片压缩
    // ReadData(file) {
    //   console.log(file);
    //   const isJpgOrPng =
    //     file.type === "image/jpeg" || file.type === "image/png" || file.type === 'image/webp';
    //   const isSize = file.size / 1024 < 64;
    //   console.log(isSize);
    //   if (!isJpgOrPng) {
    //     this.$message.error("上传图片格式不符!");
    //     return false;
    //   }
    //   return new Promise((resolve, rej) => {
    //     // 小于64kb 不压缩
    //     if (isSize) {
    //       resolve(file);
    //     } else {
    //       console.log("需要进行压缩");
    //       // 压缩到64KB,这里的64就是要压缩的大小,可自定义
    //       imageConversion.compressAccurately(file, 64).then((res) => {
    //         resolve(new window.File([res], file.name, { type: file.type }));
    //       });
    //     }
    //   });
    // },
    handleDelete(row) {
      console.log(row);
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        deleteTeacher({ user_id: row.user_id }).then(response => {
          console.log(response);
          if (response.code == 200) {
            this.fetchData();
          }
        })
      });
    }
  },
  mounted() { },
};
</script>

<style scoped>
.filterContainer {
  margin-bottom: 10px;
}

.upload {
  display: flex;
}

.dialog {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>